﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;

namespace Library
{
    public class IEContentManager : ContentManager
    {
        public IEContentManager(IServiceProvider serviceProvider)
            : base(serviceProvider) { }

        public bool PreserveAssets = true;

        List<IDisposable> disp = new List<IDisposable>();
        Dictionary<string, object> loaded = new Dictionary<string, object>();

        public override T Load<T>(string assetName)
        {
            T r = this.ReadAsset<T>(assetName, RecordIDisposable);
               
            if(PreserveAssets && !loaded.ContainsKey(assetName))
                loaded.Add(assetName,r);
            return r;
        }

        void RecordIDisposable(IDisposable assert)
        {
            if (PreserveAssets)
                disp.Add(assert);
        }

        public override void Unload()
        {
            foreach (IDisposable dis in disp)
                dis.Dispose();
            loaded.Clear();
            disp.Clear();
        }

        public void Unload(string assetName)
        {
            if (loaded.ContainsKey(assetName))
            { 
                if(loaded[assetName] is IDisposable && disp.Contains((IDisposable)loaded[assetName]))
                {
                    IDisposable ob = disp[disp.IndexOf((IDisposable)loaded[assetName])];
                    ob.Dispose();
                    disp.Remove(ob);
                }
                loaded.Remove(assetName);
            }
        }
    }
}